package main

import (
	"bufio"
	"bytes"
	"errors"
	"fmt"
)

func main() {
	datas := "*3\r\n" +
		"$3\r\n" +
		"set\r\n" +
		"$4\r\n" +
		"name\r\n" +
		"$5\r\n" +
		"pdudo\r\n"

	readers := bufio.NewReader(bytes.NewReader([]byte(datas)))
	toArgs(readers)
}

// 转换
func toArgs(rd *bufio.Reader) {
	data , _ , _ := rd.ReadLine()

	switch data[0] {
	case '*':
		n,_ := byteToInt(data[1:]) // 循环n次
		fmt.Println("循环",n,"次")
		for i:=0;i<n;i++ {
			toArgs(rd)
		}
	case '$':
		m,_ := byteToInt(data[1:]) // 获取m个数据
		fmt.Println("命令长度: " , m)

		buf := make([]byte,m)
		rd.Read(buf[:])
		fmt.Println("实际命令:",string(buf))

		crlf := make([]byte,2)
		rd.Read(crlf)
		if string(crlf) != "\r\n" {
			fmt.Println("结尾不是\r\n，异常退出")
			return
		}
	}
}

func byteToInt(number []byte) (int , error) {
	var sum int
	x := 1
	for i:=len(number)-1;i>=0;i-- {
		if number[i] < '0' || number[i] > '9' {
			return 0 , errors.New("toNumberError")
		}
		sum = int(number[i] - '0') * x
		x = x * 10
	}

	return sum,nil
}